package model

import (
	_ "github.com/go-sql-driver/mysql"

	"aglaia/global"
	"aglaia/pkg/setting"
	"fmt"
	"github.com/jinzhu/gorm"
	"time"
)

type Model struct {
	Id        uint       `json:"id" gorm:"primary_key"`
	CreatedAt time.Time  `json:"created_at"`
	UpdatedAt time.Time  `json:"updated_at"`
	DeletedAt *time.Time `json:"deleted_at"`
}

func NewDBEngine(databaseSetting *setting.DatabaseSettings) (*gorm.DB, error) {
	db, err := gorm.Open(databaseSetting.DBType,
		fmt.Sprintf("%s:%s@tcp(%s)/%s?charset=%s&parseTime=%t&loc=Local",
			databaseSetting.Username,
			databaseSetting.Password,
			databaseSetting.Host,
			databaseSetting.DBName,
			databaseSetting.Charset,
			databaseSetting.ParseTime,
		))
	if err != nil {
		return nil, err
	}

	if global.ServerSetting.RunMode == "debug" {
		db.LogMode(true)
	}

	db.SingularTable(true)

	db.DB().SetMaxIdleConns(databaseSetting.MaxIdleConnections)
	db.DB().SetMaxOpenConns(databaseSetting.MaxOpenConnections)

	db.AutoMigrate(
		&Auth{},
		&AuthRecord{},
		&Tag{},
		&Category{},
		&Article{},
		&ArticleTag{},
	)

	return db, nil
}
